package org.example.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截过滤器
 * 优化点：
 * 1. 更严格的路径匹配逻辑
 * 2. 支持AJAX请求处理
 * 3. 完整的静态资源排除
 * 4. 更清晰的日志输出
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    // 不需要登录即可访问的URL前缀
    private static final String[] EXCLUDED_PREFIXES = {
            "/VoingSystem/views/login.jsp",
            "/VoingSystem/views/relation.jsp",
            "/VoingSystem/login",
            "/VoingSystem/views/register.jsp",
            "/VoingSystem/views/forgotPassword.jsp",
            "/VoingSystem/fw/sendEmail",
            "/VoingSystem/fw/fd",
            "/VoingSystem/register",
            "/VoingSystem/static/",     // 静态资源目录
            "/VoingSystem/public/",     // 公共资源
            "/VoingSystem/favicon.ico", // 网站图标
            "/VoingSystem/error/",
            "/VoingSystem/relation",
            "/person/index"// 错误页面
    };

    // AJAX请求的响应内容
    private static final String AJAX_UNAUTHORIZED_RESPONSE =
            "{\"code\": 401, \"message\": \"未登录，请先登录\", \"redirect\": \"/views/login.jsp\"}";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录过滤器初始化完成");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false); // 不创建新Session

        String uri = request.getRequestURI();
        String method = request.getMethod();
        boolean isExcluded = isExcludedURI(uri);

        // 日志输出
        System.out.printf("[LoginFilter] 请求: %s %s, 放行: %s%n",
                method, uri, isExcluded ? "yes" : "no");

        // 1. 排除列表中的URL直接放行
        if (isExcluded) {
            chain.doFilter(request, response);
            return;
        }

        // 2. 检查登录状态
        boolean isLoggedIn = session != null && session.getAttribute("person") != null;

        if (isLoggedIn) {
            // 已登录，放行请求
            chain.doFilter(request, response);
        } else {
            // 普通请求重定向到登录页
            String redirectUrl = request.getContextPath() + "/views/login.jsp";
            if (session != null) {
                session.setAttribute("loginMessage", "请先登录");
            }
            String encodedRedirect = response.encodeRedirectURL(redirectUrl);
            response.sendRedirect(encodedRedirect);

        }
    }

    @Override
    public void destroy() {
        System.out.println("登录过滤器销毁");
    }

    /**
     * 判断请求是否属于排除列表
     */
    private boolean isExcludedURI(String uri) {
        for (String prefix : EXCLUDED_PREFIXES) {
            if (uri.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为AJAX请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String xhrHeader = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(xhrHeader);
    }
}